<template>
  <div class="tw-main">
    <div class="screen">
      <el-row class="tw-grid">
        <el-col :md="24" :lg="8" class="tw-grid__left">
          <!-- <tw-card
          :label="$t('m.apiQuota')"
          > -->
          <tw-card
          :label="'API关键指标'"
          :heightCard="'935px'"
          >
            <el-row>
              <el-col :md="12" :lg="24">
                <div class="tw-box">
                  <tw-echarts
                    id="echarts_apiKeyIndicatorOne"
                    ref="echarts_apiKeyIndicatorOne"
                    :additionalOptions="additionalOptions['echarts_apiKeyIndicatorOne']"
                    height="432px"
                  ></tw-echarts>
                </div>
              </el-col>
              <el-col :md="12" :lg="24">
                <div class="tw-box">
                  <tw-echarts
                    id="echarts_apiKeyIndicatorTwo"
                    ref="echarts_apiKeyIndicatorTwo"
                    :additionalOptions="additionalOptions['echarts_apiKeyIndicatorTwo']"
                    height="432px"
                  ></tw-echarts>
                </div>
              </el-col>
            </el-row>
          </tw-card>
        </el-col>
        <el-col :md="24" :lg="16" class="tw-grid__right">
          <!-- <tw-card
          :label="$t('m.apiRequestTread')"
          > -->
          <tw-card
          :label="'最近API调用变化'"
          :heightCard="'935px'"
          >
            <div class="tw-box">
              <tw-echarts
                id="echarts_APIChangeTrend"
                ref="echarts_APIChangeTrend"
                :additionalOptions="additionalOptions['echarts_APIChangeTrend']"
                height="378px"
              ></tw-echarts>
            </div>
            <div class="tw-box">
              <tw-table
                class="medium-height"
                :tableData="tableData"
                :maxItem="8"></tw-table>
            </div>
          </tw-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script scoped>
import TwCard from '@/components/TwCard.vue'
import TwEcharts from '@/components/TwEcharts.vue'
import TwTable from '@/components/TwTable.vue'
import configUtil from '@/config/config'
import echarts from 'echarts'

export default{
  created () {
    let vm = this
    // this.getApiRequest()
    // let lineChartData = {
    //   'note': vm.$i18n.messages[vm.$i18n.locale].m.requestCount,
    //   'xAxisData': [],
    //   'seriesName': vm.$i18n.messages[vm.$i18n.locale].m.requestCount,
    //   'seriesData': []
    // }
    // vm.additionalOptions.echarts_APIChangeTrend = lineChartData
    this.getApiRecordInfo()
    // setInterval(function () {
    //   vm.getApiRequest()
    //   vm.getApiRecordInfo()
    // }, 5 * 60 * 1000)

    vm.$axios.get(window.location.origin + '/static/weishidataview/jsondata/echarts_apiKeyIndicatorOne.json').then(response => {
      vm.additionalOptions.echarts_apiKeyIndicatorOne = response.data
      // console.log('api关键指标1=========', response.data)
    }, response => {
      console.log('error')
    })

    vm.$axios.get(window.location.origin + '/static/weishidataview/jsondata/echarts_apiKeyIndicatorTwo.json').then(response => {
      vm.additionalOptions.echarts_apiKeyIndicatorTwo = response.data
    }, response => {
      console.log('error')
    })

    // vm.$axios.get(window.location.origin + '/static/weishidataview/jsondata/echarts_APIChangeTrend.json').then(response => {
    //   vm.additionalOptions.echarts_APIChangeTrend = response.data
    // }, response => {
    //   console.log('error')
    // })

    // 查询应用列表
    // vm.$axios.post('/openapi-uc/app/list', {}).then(res => {
    //   // vm.additionalOptions.echarts_APIChangeTrend = res.data
    //   console.log('查询应用列表============', res.data)

    //   if (res.data.pageInfo && res.data.serverResult.resultCode === '200') {
    //     console.log('查询应用列表============', res.data.pageInfo.list)
    //   }
    // }, res => {
    //   console.log('error')
    // })

    // 最近API调用变化
    vm.$axios.post(configUtil.getApiPath() + 'apirequest/getApiRecordRequest', null).then(res => {
      // console.log('测试接口是否OK111111111', res.data.apiCountList)
      res.data.apiCountList.forEach((item, index) => {
        vm.additionalOptions.echarts_APIChangeTrend.xAxisData.push(item.time)
        vm.additionalOptions.echarts_APIChangeTrend.seriesData.push(item.totalCount)
      })

      // api 接口调用
      // console.log('res.data.apiRecordList==========', res.data.apiRecordList)
      res.data.apiRecordList.forEach((item, index) => {
        vm.tableData.tbody[index].item1 = item.apiPath
        vm.tableData.tbody[index].item2 = item.requestTime
        vm.tableData.tbody[index].item3 = item.spendTime
      })
    })
  },
  mounted () {
    window.onresize = () => {
      this.$refs['echarts_apiKeyIndicatorOne'].resizeChart()
      this.$refs['echarts_apiKeyIndicatorTwo'].resizeChart()
      this.$refs['echarts_APIChangeTrend'].resizeChart()
    }
    // 模拟表格数据
    // setInterval(() => {
    //   if (this.tableData.tbody.length > 8) {
    //     this.tableData.tbody.shift()
    //     if (this.apiRecordIndex > this.tableData.tbody.length - 1) {
    //       this.apiRecordIndex = 0
    //     }
    //     this.tableData.tbody.push(this.apiRecordArray[this.apiRecordIndex])
    //     this.apiRecordIndex++
    //   }
    // }, 1000)
  },
  destroyed () {
    if (this.timeIntervalId) {
      clearInterval(this.timeIntervalId)
    }
  },
  props: [],
  data () {
    return {
      additionalOptions: {
        echarts_apiKeyIndicatorOne: {},
        echarts_apiKeyIndicatorTwo: {},
        echarts_APIChangeTrend: {
          note: '最新一周API调用变化趋势',
          xAxisData: [],
          seriesName: '次数',
          seriesData: []
        }
      },
      apiRecordArray: [],
      apiRecordIndex: 0,
      simulationControl1: true,
      tableData: {
        thead: [
          {
            value: '接口名称',
            width: '60%'
          },
          {
            value: '请求时间',
            width: '25%'
          },
          {
            value: '请求耗时(毫秒)',
            width: '20%'
          }
          // {
          //   value: '调用次数',
          //   width: '20%'
          // },
          // {
          //   value: '失败率',
          //   width: '20%'
          // },
          // {
          //   value: '平均耗时(毫秒)',
          //   width: '20%'
          // },
          // {
          //   value: '最大耗时(毫秒)',
          //   width: '20%'
          // }
        ],
        tbody: [
          {
            item1: 'http:/openapi-uc/uc/getuserrightlist',
            item2: '2020-09-22 09:21:54',
            item3: 56
          },
          {
            item1: 'http:/openapi-uc/system/platconfig',
            item2: '2020-09-20 10:21:50',
            item3: 23
          },
          {
            item1: 'http:/openapi-uc/uc/getuserrightlist',
            item2: '2020-09-21 11:21:00',
            item3: 56
          },
          {
            item1: 'http:/openapi-uc/uc/getuserbytoken/4ce50482a53f112',
            item2: '2020-09-23 09:22:54',
            item3: 76
          },
          {
            item1: 'http:/fs/media/paas01/2020/7/21/jpg/299ac28b-ecb2-',
            item2: '2020-09-19 09:20:51',
            item3: 12
          },
          {
            item1: 'http:/openapi-uc/oauth/checktoken',
            item2: '2020-09-22 09:30:52',
            item3: 89
          },
          {
            item1: 'http:/openapi-uc/oauth/token',
            item2: '2020-09-20 09:22:52',
            item3: 23
          },
          {
            item1: 'http:/openapi-uc/uc/checkuserrepeat',
            item2: '2020-09-21 19:21:55',
            item3: 20
          }
        ]
      },
      apiTimeArray: [],
      apiCountArray: [],
      timeIntervalId: 0
    }
  },
  components: {
    TwCard,
    TwEcharts,
    TwTable
  },
  methods: {
    /*
    simulation1: function () {
      // 完成渲染后绑定事件，模拟动态
      // 此处涉及到标签的颜色，方式1为重置additionalOptions，通过组件重新渲染，但是注意事件的重叠触发。
      // 配置项设置中已经根据数据定义好了标签颜色
      if (this.simulationControl1) {
        setInterval(() => {
          this.additionalOptions.echarts_apiKeyIndicatorOne.value = parseInt(Math.random() * 10000)
        }, 3000)
        // 图表渲染完成后此事件会重复触发，确保seiInterval只触发一次
        this.simulationControl1 = false
      }
    },
    simulation2: function () {
      // 完成渲染后绑定事件，模拟动态
      // 这是直接在页面进行设置，开销要低一些
      const colors = ['#00fffc', '#ffdb84', '#fb6c84']
      let chart = echarts.init(document.getElementById('echarts_apiKeyIndicatorTwo'))
      let chartOption = chart.getOption()
      setInterval(function () {
        chartOption.series[0].data[0].value = (Math.random() * 100).toFixed(2)
        // 这里是模块内处理颜色的逻辑
        if (chartOption.series[0].data[0].value <= chartOption.series[0].max * 0.3) {
          chartOption.series[0].detail.color = colors[0]
        } else if (chartOption.series[0].data[0].value <= chartOption.series[0].max * 0.7) {
          chartOption.series[0].detail.color = colors[1]
        } else if (chartOption.series[0].data[0].value <= chartOption.series[0].max) {
          chartOption.series[0].detail.color = colors[2]
        }
        chart.setOption(chartOption)
      }, 3000)
    },
    */
    simulation3 () {
      this.timeIntervalId = setInterval(() => {
        // console.log('start to change ....')
        let chart = echarts.init(document.getElementById('echarts_APIChangeTrend'))
        let chartOption = chart.getOption()
        let obj1 = chartOption.xAxis[0].data.shift()
        chartOption.xAxis[0].data.push(obj1)
        let obj2 = chartOption.series[0].data.shift()
        chartOption.series[0].data.push(obj2)
        chart.setOption(chartOption)
      }, 1000)
    },
    getApiRequest () {
      let vm = this
      let title2 = vm.$i18n.messages[vm.$i18n.locale].m.failedRatio
      let title1 = vm.$i18n.messages[vm.$i18n.locale].m.requestCountEvery30Seconds
      this.$axios.post(configUtil.getApiPath() + 'apirequest/getApiRecordRequest', null).then(response => {
        let data = response.data
        if (data) {
          if (data.apiRecordList) {
            // 请求数
            let requestCount = data.requestCount * 5
            // 失败率
            let failedRatio = data.failedTime.toFixed(2) - 0

            let apiCountChartData = {
              'note': '',
              'max': 10000,
              'seriesName': '',
              'value': requestCount,
              'title': title1
            }
            vm.additionalOptions.echarts_apiKeyIndicatorOne = apiCountChartData

            let apiFailedChartData = {
              'note': title2,
              'max': 1,
              'seriesName': title2,
              'value': failedRatio,
              'title': title2
            }
            vm.additionalOptions.echarts_apiKeyIndicatorTwo = apiFailedChartData

            vm.tableData.tbody = []
            let list = data.apiRecordList
            for (let i = 0; i < list.length; i++) {
              let tableLine = {'item1': list[i].apiPath, 'item2': list[i].requestTime, 'item3': list[i].spendTime}
              vm.tableData.tbody.push(tableLine)
              vm.apiRecordArray.push(tableLine)
            }
          }
        }
      }, response => {
        console.log('error')
      })
    },
    getApiRecordInfo () {
      let vm = this
      vm.apiTimeArray = []
      vm.apiCountArray = []
      this.$axios.post(configUtil.getApiPath() + 'apirequest/getApiRequestCountList', {'type': '1'}).then(response => {
        let data = response.data
        if (data && data.pageInfo && data.pageInfo.list && data.pageInfo.list.length > 0) {
          let startCount = data.pageInfo.list.length - 100
          if (startCount < 0) {
            startCount = 0
          }
          for (let i = 0; i < data.pageInfo.list.length; i++) {
            if (i < startCount) {
              continue
            }
            let time = data.pageInfo.list[i].staTime
            if (time && time.length > 8) {
              time = time.substr(time.length - 8)
            }
            vm.apiTimeArray.push(time)
            vm.apiCountArray.push(data.pageInfo.list[i].requestCount * 10)
          }
          vm.setApiCountLineData()
        }
      }, response => {
        console.log('error')
      })
    },
    setApiCountLineData () {
      clearInterval(this.timeIntervalId)
      let title3 = this.$i18n.messages[this.$i18n.locale].m.requestCount
      let lineChartData = {
        'note': title3,
        'xAxisData': this.apiTimeArray,
        'seriesName': title3,
        'seriesData': this.apiCountArray
      }
      this.additionalOptions.echarts_APIChangeTrend = lineChartData
      this.simulation3()
    }
  }
}
</script>

<style scoped></style>
